package com.turnos.ws;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.*;
import javax.xml.ws.soap.SOAPBinding;

import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.InputStream;

public class ClienteImprimir {

	private String XXX = "XXX";
	// private String nombreWebService = "turnoTicket";
	private String nombreMetodo = "imprimir";
	private String nombreMetodoLocal = "tns";

	private String IP_PORT = "http://localhost:8090";
	private String URL_TEMPLATE = XXX + "/turnoTicket/";
	private String pathQName = "http://imprimir.turnos.ovevete.com/";

	/**
	 * Invoca al WebService donde está la impresora de tickets
	 * 
	 * @param ip_port
	 *            Ej: http://10.25.3.1:8090
	 * @param numero
	 *            Ej: A 3
	 * @param cliente
	 *            : Juan Perez
	 * @param ruc_ci
	 *            2.345.678
	 * @param hora
	 *            12:32
	 * @return 0 si todo ok, Ver códigos de error en Cosntantes.java
	 * @throws Exception
	 */
	public int imprimir(String ip_port, String numero, String cliente,
			String ruc_ci, String hora) {

		int ok = 0;

		try {

			String url = this.URL_TEMPLATE.replaceAll(XXX, ip_port);

			SOAPMessage soapMessage = getSoapMessage();
			SOAPBody soapBody = soapMessage.getSOAPBody();

			SOAPElement operation = soapBody.addChildElement(nombreMetodo,
					nombreMetodoLocal);

			String prefix = nombreMetodoLocal;
			SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();

			QName paramNameNumero = envelope.createQName("numero", prefix);// ,
			QName paramNamecliente = envelope.createQName("cliente", prefix);// ,
			QName paramNameruc_ci = envelope.createQName("ruc_ci", prefix);// ,
			QName paramNamehora = envelope.createQName("hora", prefix);// ,
																		// url);

			operation.addChildElement(paramNameNumero).addTextNode(numero);
			operation.addChildElement(paramNamecliente).addTextNode(cliente);
			operation.addChildElement(paramNameruc_ci).addTextNode(ruc_ci);
			operation.addChildElement(paramNamehora).addTextNode(hora);

			soapMessage.saveChanges();

			SOAPConnection soapConnection = getSoapConnection();
			try {
				SOAPMessage soapMessageReply = soapConnection.call(soapMessage,
						url);

				SOAPPart soapPart = soapMessageReply.getSOAPPart();
				SOAPEnvelope envelope2 = soapPart.getEnvelope();
				SOAPBody body = envelope2.getBody();
				Iterator iter = body.getChildElements();
				Node resultOuter = (Node) ((Node) iter.next()).getFirstChild();
				Node result = (Node) resultOuter.getFirstChild();
				String value = result.getNodeValue();
				ok = Integer.parseInt(value.trim());
			} catch (Exception e) {
				ok = -1;
				e.printStackTrace();
			}

			soapConnection.close();

		} catch (Exception e) {
			ok = -1;
			e.printStackTrace();
		}

		return ok;
	}

	private SOAPElement createElement(String localName, String nsPrefix,
			String nsURI, String value) throws SOAPException {
		SOAPElement soapElement = SOAPFactory.newInstance().createElement(
				localName, nsPrefix, nsURI);
		soapElement.addTextNode(value);
		return soapElement;
	}

	private SOAPMessage getSoapMessage() throws SOAPException {
		MessageFactory messageFactory = MessageFactory.newInstance();
		SOAPMessage soapMessage = messageFactory.createMessage();

		// Object for message parts
		SOAPPart soapPart = soapMessage.getSOAPPart();
		SOAPEnvelope envelope = soapPart.getEnvelope();

		envelope.addNamespaceDeclaration("xsd",
				"http://www.w3.org/2001/XMLSchema");
		envelope.addNamespaceDeclaration("xsi",
				"http://www.w3.org/2001/XMLSchema-instance");
		envelope.addNamespaceDeclaration("enc",
				"http://schemas.xmlsoap.org/soap/encoding/");
		envelope.addNamespaceDeclaration("env",
				"http://schemas.xmlsoap.org/soap/envelop/");

		envelope.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");

		// add the technet namespace as "technet"
		envelope.addNamespaceDeclaration(nombreMetodoLocal, pathQName);

		return soapMessage;
	}

	private SOAPConnection getSoapConnection()
			throws UnsupportedOperationException, SOAPException {
		SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory
				.newInstance();
		SOAPConnection soapConnection = soapConnectionFactory
				.createConnection();

		return soapConnection;
	}

	public static void main(String[] args) throws Exception {
		ClienteImprimir cd = new ClienteImprimir();
		int out = cd.imprimir("http://192.168.0.105:8090", "numero","cliente", "ruc_ci", "hora");
		System.out.println("Resultado:" + out);


	}
	
	
}
